// goods-cart.js
var iFDU = require('../../utils/iFDU.js');
var app = getApp();
Page({
  data: {
    config: app.config,
    globalData: app.globalData,

    items: [],
    totalPrice: 0,
    selectAll: false,
    selectedCount: 0,
    emptyPageData: {
      message: '购物车中无一物',
      buttonText: '去首页逛逛',
      buttonEvent: 'goHome'
    }
  },

  onLoad: function (options) {
  },

  onShow: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    });
    app.getUserInfo(function (globalData) {
      that.setData({
        globalData: globalData
      });

      iFDU.api.doGet(
        'cart/getCartList',
        {
          userId: globalData.userId,
          rnd: Math.random()
        },
        function (data) {
          var items = data;
          for (var index in items) {
            var item = items[index];
            item['selected'] = 1;
          }

          that.setData({
            items: data
          });

          that.caculateTotalPrice();
          that.determineSelectAll();
          wx.hideLoading();
        }
      )
    });
  },

  updateCartItemCount: function (goodsId, count) {
    var that = this;
    iFDU.api.doGet(
      'cart/updateCartItemCount',
      {
        userId: that.data.globalData.userId,
        subProductId: goodsId,
        count: count,
        rnd: Math.random()
      },
      function (data) {
        
      }
    )
  },

  minus: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      if (item['goods_id'] == id) {
        var count = item['goods_count'];
        if (count > 1) {
          item['goods_count'] = count - 1;
          that.updateCartItemCount(id, count - 1);
        }
        break;
      }
    }

    

    that.setData({
      items: items
    });

    that.caculateTotalPrice();
  },
  plus: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      if (item['goods_id'] == id) {
        var count = item['goods_count'];
        item['goods_count'] = count + 1;
        that.updateCartItemCount(id, count + 1);
        break;
      }
    }

    

    that.setData({
      items: items
    });

    that.caculateTotalPrice();
  },

  caculateTotalPrice: function () {
    var that = this;
    var items = that.data.items;
    var totalPrice = 0;
    for (var index in items) {
      var item = items[index];
      if (item['selected'] == 1) {
        var count = item['goods_count'];
        // 商品价格
        var price = item['subProductView']['channelPrice'];
        totalPrice += price * count;

        // 营销商品价格
        if (item['marketing_goods_propertie_ids'] 
        && item['marketing_goods_propertie_ids'] != '' 
        && item['marketing_goods_propertie_ids'] != '-1' 
        && item['mainMarketingProductViewList'] 
        && item['mainMarketingProductViewList'].length > 0) {
          for (var j in item['mainMarketingProductViewList']) {
            if (item['mainMarketingProductViewList'][j]['selectedSubPrice']) {
              totalPrice += item['mainMarketingProductViewList'][j]['selectedSubPrice'] * count;
            }
          }
        }
      }
    }

    that.setData({
      totalPrice: totalPrice
    });
  },

  determineSelectAll: function () {
    var that = this;
    var items = that.data.items;
    var selectAll = true;
    var selectedCount = 0;
    if (items && items.length > 0) {
      for (var index in items) {
        var item = items[index];
        if (item['selected'] == 0) {
          selectAll = false;
        } else {
          selectedCount ++;
        }
      }
    } else {
      selectAll = false;
    }

    that.setData({
      selectAll: selectAll,
      selectedCount: selectedCount
    });
  },

  selectCartItem: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      if (item['goods_id'] == id) {
        item['selected'] = 1;
      }
    }

    that.setData({
      items: items
    });

    that.caculateTotalPrice();
    that.determineSelectAll();
  },

  deselectCartItem: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      if (item['goods_id'] == id) {
        item['selected'] = 0;
      }
    }

    that.setData({
      items: items
    });

    that.caculateTotalPrice();
    that.determineSelectAll();
  },

  deleteSingleCartItem: function (e) {
    var id = e.currentTarget.dataset.id;
    this.deleteCartItem(id);
  },

  deleteSelectedCartItems: function (e) {
    var that = this;
    var items = that.data.items;
    var result = [];
    for (var index in items) {
      var item = items[index];
      if (item['selected'] == 1) {
        result.push(item['goods_id']);
      }
    }
    if (result.length > 0) {
      this.deleteCartItem(result.join(','));
    }
  },

  deleteCartItem: function (ids) {
    var that = this;
    wx.showModal({
      title: '删除购物车商品',
      content: '将所选商品从购物车中删除吗？',
      confirmText: "删除",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          iFDU.api.doGet(
            'cart/deleteCartItems',
            {
              userId: that.data.globalData.userId,
              subProductIds: ids,
              rnd: Math.random()
            },
            function (data) {
              var items = that.data.items;
              if (items.length > 0) {
                var results = [];
                for (var index in items) {
                  if ((',' + ids + ',').indexOf(',' + items[index]['goods_id'] + ',') > -1) {

                  } else {
                    results.push(items[index]);
                  }
                }
                that.setData({
                  items: results
                });

                that.caculateTotalPrice();
                that.determineSelectAll();
              }
            }
          )
        }
      }
    });
  },

  selectAll: function (e) {
    var that = this;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      item['selected'] = 1;
    }

    that.setData({
      selectAll: true,
      items: items
    });

    that.caculateTotalPrice();
    that.determineSelectAll();
  },

  deselectAll: function (e) {
    var that = this;
    var items = that.data.items;
    for (var index in items) {
      var item = items[index];
      item['selected'] = 0;
    }

    that.setData({
      selectAll: false,
      items: items
    });

    that.caculateTotalPrice();
    that.determineSelectAll();
  },

  goConfirm: function (e) {
    var that = this;
    var items = that.data.items;
    console.log('cart items', items)
    var goodsList = [];
    for (var index in items) {
      var item = items[index];
      if (item['selected'] == 1) {
        var goods = {
          goods_id: item['goods_id'],
          goods_count: item['goods_count'],
          goods_logo: item['subProductView']['logo'],
          goods_main_id: item['mainProductView']['id'],
          goods_title: item['mainProductView']['title'],
          is_need_figure: item['mainProductView']['is_need_figure'],
          is_broider: item['mainProductView']['is_broider'],
          is_virtual: item['mainProductView']['is_virtual'],
          goods_price: item['subProductView']['channelPrice'],
          sleeve_word: '',
          sleeve_word_type: 1
        };

        if (item['marketing_goods_propertie_ids'] && item['marketing_goods_propertie_ids'] != '' && item['marketing_goods_propertie_ids'] != '-1') {
          // goods['marketing_goods_propertie_ids'] = item['marketing_goods_propertie_ids'];
          goods['marketing_goods_propertie_ids'] = item['marketing_goods_propertie_ids'].split(',');
          var marketingGoodsNames = [];
          var marketingNames = [];
          var marketingGoodsProperties = [];
          for (var index in item['mainMarketingProductViewList']) {
            var bodyInsur = item['mainMarketingProductViewList'][index];
            if (bodyInsur.selectedSubName && bodyInsur.selectedSubName != undefined && bodyInsur.selectedSubName != '') {
              marketingGoodsNames.push(bodyInsur.selectedSubName + ' | ￥' + (bodyInsur.selectedSubPrice / 100.00));
              marketingNames.push(bodyInsur.name)
              marketingGoodsProperties.push({
                id: bodyInsur.id,
                name: bodyInsur.name,
                price: bodyInsur.selectedSubPrice
              });
            }
          }
          goods['marketing_goods_properties'] = marketingGoodsProperties;
          // goods['marketing_goods_propertie_names'] = marketingGoodsNames.join(' ');
          goods['marketing_goods_propertie_names'] = marketingGoodsNames;
          goods['marketing_properties_names'] = marketingNames;
          // }
          // goods['marketing_goods_properties'] = marketingGoodsProperties;
          // goods['marketing_goods_propertie_names'] = marketingGoodsNames.join(' ');
        }
        
        if (item['subProductView']['subSkus'] && item['subProductView']['subSkus'].length > 0) {
          var subSkus = [];
          for (var index in item['subProductView']['subSkus']) {
            var subSku = {
              id: item['subProductView']['subSkus'][index]['id'],
              name: item['subProductView']['subSkus'][index]['name']
            };
            subSkus.push(subSku);
          }
          goods['subSkus'] = subSkus;
        }
        goodsList.push(goods);
      }
    }
    if (goodsList.length < 1) {
      iFDU.toast.showToast({
        title: '请选择要结算的商品',
        mask: false
      })
      return;
    }
    wx.setStorageSync('goodsList', JSON.stringify(goodsList));
    wx.navigateTo({
      url: '../order-confirm/order-confirm?fromCart=true&virtual=0',
    })
  },

  showGoodsDetail: function (e) {
    wx.navigateTo({
      url: '../goods-item/goods-item?goodsId=' + e.currentTarget.dataset.id,
    })
  },

  goHome: function (e) {
    wx.switchTab({
      url: '../home/home',
    })
  },
  
  onShareAppMessage: function (res) {
    var that = this;
    return {
      title: '爱上衬衫，从「逸见」开始…',
      imageUrl: 'http://s.i-fdu.com/runto/wxa/s/yjshare.jpeg',
      path: 'pages/home/home',
      success: function (res) {
      },
      fail: function (res) {
      }
    }
  }
})